package com.hippy.erya.config.properties;

import cn.stylefeng.roses.core.datascope.DataScopeInterceptor;
import cn.stylefeng.roses.core.dbid.GunsDatabaseIdProvider;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.hippy.erya.sys.core.constant.cache.Cache;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.FileSystemResource;

import java.util.Objects;


@Configuration
@Conditional(LinuxCondition.class)
public class BjPropertiesConfig {


    @Bean
    public PropertySourcesPlaceholderConfigurer loadLinuxProperties(ApplicationContext context) {
        PropertySourcesPlaceholderConfigurer configure = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new FileSystemResource(getResourceLocation(context)));
        configure.setProperties(Objects.requireNonNull(yaml.getObject()));
        return configure;
    }

    private String getResourceLocation(ApplicationContext context) {
        String[] activeProfiles = context.getEnvironment().getActiveProfiles();
        return context.getEnvironment().getProperty(Cache.LINUX_PROPERTIES_LOCATION) +
                Cache.PREFIX_NAME + activeProfiles[0] + Cache.SUFFIX_NAME;
    }

    // 以下是因为采用的磁盘文件当作配置文件, MybatisPlus的一些插件无法自动导入需要手动导入

    /**
     * mybatis-plus分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }


    /**
     * 数据范围mybatis插件
     */
    @Bean
    @ConditionalOnMissingBean
    public DataScopeInterceptor dataScopeInterceptor() {
        return new DataScopeInterceptor();
    }

    /**
     * 乐观锁mybatis插件
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

    /**
     * 数据库id选择器
     */
    @Bean
    @ConditionalOnMissingBean
    public GunsDatabaseIdProvider gunsDatabaseIdProvider() {
        return new GunsDatabaseIdProvider();
    }

}
